package com.qubi.exchange.message;

import lombok.Data;

import java.nio.ByteBuffer;

@Data
public class BufferMessage {
    byte[]data;
    int messageType;
    int gzip;
    public byte[]toBytesArray()
    {
        int dataLen=0;
        if(data==null)dataLen=0;
        else dataLen=data.length;
        int mask=0;
        mask=((messageType<<8)&0xFFFFFF00)+(gzip&0xFF);
        var  byteBuffer=ByteBuffer.allocate(4+dataLen).array();
        byte[] maskBytes=intToByteArray(mask);
        System.arraycopy(maskBytes,0,byteBuffer,0,4);
        if(data!=null) System.arraycopy(data,0,byteBuffer,4,dataLen);
        return byteBuffer;
    }



    public static byte[] intToByteArray(int i) {
        byte[] result = new byte[4];
        result[0] = (byte)((i >> 24) & 0xFF);
        result[1] = (byte)((i >> 16) & 0xFF);
        result[2] = (byte)((i >> 8) & 0xFF);
        result[3] = (byte)(i & 0xFF);
        return result;
    }
    public BufferMessage()
    {

    }
    BufferMessage(int messageType,int gzip,byte []data){
        this.messageType=messageType;
        this.gzip=gzip;
        this.data=data;

    }

    BufferMessage(byte[]data)
    {
        makeData(data);
    }
    public void makeData(byte[]data){
        int mask=byteArrayToInt(data);
        this.data=ByteBuffer.allocate(data.length-4).array();
        System.arraycopy(data,4,this.data,0,data.length-4);
        messageType=(mask>>8)&0x00FFFFFF;
        gzip=mask&0x000000FF;


    }


    public static int byteArrayToInt(byte[] bytes) {
        int value=0;
        for(int i = 0; i < 4; i++) {
            int shift= (3-i) * 8;
            value +=(bytes[i] & 0xFF) << shift;
        }
        return value;
    }

    public static void main(String[] args) {
        BufferMessage bufferMessage=new BufferMessage();
        bufferMessage.messageType=254;
        bufferMessage.gzip=1;
        byte[]data={1,2,3,4,-6,5};
        bufferMessage.setData(data);
        byte[]n=bufferMessage.toBytesArray();


        BufferMessage buffer=new BufferMessage(n);
        System.out.println(buffer);


    }

}
